package com.wk.note;//package com.example.conceptnotebookjava;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeHookException;
import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent;
import com.github.kwhat.jnativehook.keyboard.NativeKeyListener;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
//import org.jnativehook.GlobalScreen;
//import org.jnativehook.NativeHookException;
//import org.jnativehook.keyboard.NativeKeyEvent;
//import org.jnativehook.keyboard.NativeKeyListener;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConceptNotebookApp extends Application {

    private NoteFileManager noteFileManager = new NoteFileManager();
    private ObservableList<Note> notes = FXCollections.observableArrayList();

    private ListView<Note> noteListView;
    private TextArea contentTextArea;

    private Stage primaryStage;

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 800, 600);

        VBox leftBox = new VBox();
        leftBox.setPadding(new Insets(10));
        leftBox.setSpacing(10);

        Label categoryLabel = new Label("Categories");
        ListView<String> categoryListView = new ListView<>();
        categoryListView.getItems().addAll("Work", "Personal", "Meeting", "Other");

        Label tagLabel = new Label("Tags");
        ListView<String> tagListView = new ListView<>();
        // Add tags dynamically from notes

        leftBox.getChildren().addAll(categoryLabel, categoryListView, tagLabel, tagListView);

        VBox centerBox = new VBox();
        centerBox.setPadding(new Insets(10));
        centerBox.setSpacing(10);

        noteListView = new ListView<>();
        loadNotes();
        noteListView.setItems(notes);
        noteListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                showNoteDetail(newValue);
            }
        });

        centerBox.getChildren().addAll(new Label("Notes"), noteListView);

        contentTextArea = new TextArea();
        contentTextArea.setEditable(false);
        centerBox.getChildren().add(contentTextArea);

        root.setLeft(leftBox);
        root.setCenter(centerBox);

        MenuBar menuBar = new MenuBar();
        Menu fileMenu = new Menu("File");
        MenuItem newNoteMenuItem = new MenuItem("New Note");
        newNoteMenuItem.setOnAction(event -> showNewNoteDialog());
        fileMenu.getItems().add(newNoteMenuItem);
        menuBar.getMenus().add(fileMenu);
        root.setTop(menuBar);

        primaryStage.setTitle("Concept Notebook");
        primaryStage.setScene(scene);
        primaryStage.show();

        // Register global shortcut to toggle visibility
        registerGlobalShortcut();

        // Initialize JNativeHook for global shortcut
        initJNativeHook();
    }

    private void registerGlobalShortcut() {
        // No-op method since using JNativeHook for global shortcut
    }


    private void initJNativeHook() {
        try {
            // Enable JNativeHook logging to detect possible issues
            Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
            logger.setLevel(Level.WARNING);

            // Register the listener for global key events
            GlobalScreen.registerNativeHook();
            GlobalScreen.addNativeKeyListener(new NativeKeyListener() {
                @Override
                public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
                    // Handle the global key press event
                    if (NativeKeyEvent.getKeyText(nativeKeyEvent.getKeyCode()).equals("D") &&
                            (nativeKeyEvent.getModifiers() & NativeKeyEvent.CTRL_MASK) != 0) {
                        toggleVisibility();
                    }
                }

                @Override
                public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {
                    // Handle key release if needed
                }

                @Override
                public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {
                    // Handle key typed if needed
                }
            });
        } catch (NativeHookException e) {
            e.printStackTrace();
        }
    }

    private void toggleVisibility() {
        if (primaryStage.isShowing()) {
            Platform.runLater(() -> primaryStage.hide());
        } else {
            Platform.runLater(() -> primaryStage.show());
        }
    }

    private void loadNotes() {
        List<Note> loadedNotes = noteFileManager.loadAllNotes();
        notes.addAll(loadedNotes);
    }

    private void showNoteDetail(Note note) {
        contentTextArea.setText(note.getContent());
    }

    private void showNewNoteDialog() {
        Dialog<Note> dialog = new Dialog<>();
        dialog.setTitle("New Note");
        dialog.setHeaderText("Create a new note");

        TextField titleField = new TextField();
        titleField.setPromptText("Title");

        TextArea contentArea = new TextArea();
        contentArea.setPromptText("Content");

        ComboBox<String> categoryComboBox = new ComboBox<>();
        categoryComboBox.getItems().addAll("Work", "Personal", "Meeting", "Other");
        categoryComboBox.setPromptText("Category");

        TextField tagsField = new TextField();
        tagsField.setPromptText("Tags");

        VBox dialogContent = new VBox(10);
        dialogContent.getChildren().addAll(titleField, contentArea, categoryComboBox, tagsField);
        dialog.getDialogPane().setContent(dialogContent);

        ButtonType saveButtonType = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        dialog.setResultConverter(buttonType -> {
            if (buttonType == saveButtonType) {
                return new Note(
                        null,
                        null, // filename字段暂时不需要在此处设置
                        titleField.getText(),
                        contentArea.getText(),
                        tagsField.getText(),
                        categoryComboBox.getValue()
                );
            }
            return null;
        });

        dialog.showAndWait().ifPresent(note -> {
            noteFileManager.createTempNoteFile(note); // Create temporary note file
            notes.add(note);
        });
    }

    public static void main(String[] args) {
        H2Database.createTables(); // Ensure tables are created when starting the app
        launch(args);
    }
}
